package com.xfzcode.service.impl;

import com.xfzcode.pojo.CommonEntity;
import com.xfzcode.service.ElasticsearchIndexService;
import org.elasticsearch.client.IndicesClient;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @Author XMLee
 * @Date 2022年08月23日 23:00
 * @Description:
 */
@Service
public class ElasticsearchIndexServiceImpl implements ElasticsearchIndexService {


    @Resource
    private RestHighLevelClient client;

    /**
     * 新增索引+映射
     * @param commonEntity
     * @return
     * @throws Exception
     */
    @Override
    public boolean addIndexAndMapping(CommonEntity commonEntity) throws Exception{
        //创建索引请求
        CreateIndexRequest request = new CreateIndexRequest(commonEntity.getIndexName());

        //获取前端参数
        Map<String, Object> map = commonEntity.getMap();
        //遍历外map，判断是setting还是mapping
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if ("setting".equals(entry.getKey())) {
                if (entry.getValue() instanceof Map && ((Map<?, ?>) entry.getValue()).size() > 0) {
                    request.settings((Map<String, Object>) entry.getValue());
                }
            }

            if ("mapping".equals(entry.getKey())) {
                if (entry.getValue() instanceof Map && ((Map<?, ?>) entry.getValue()).size() > 0) {
                    request.mapping((Map<String, Object>) entry.getValue());
                }
            }
        }
        //创建随意操作的客户端
        IndicesClient indicesClient = client.indices();
        //创建相应对象
        CreateIndexResponse createIndexResponse = indicesClient.create(request, RequestOptions.DEFAULT);
        return createIndexResponse.isAcknowledged();
    }

}
